<?php

namespace app\models;
use yii\db\ActiveRecord;
use Yii;

class User extends ActiveRecord
{
    public $rememberMe=true;
    public $loginname;
    public $repass;
    public static function tableName(){
        return "{{%user}}";
    }
    public function attributeLabels(){
        return[
            'username' => '用户名',
            'useremail' => '电子邮箱',
            'userpass' => '用户密码',
            'repass' => '确认密码',
            'loginname' => '用户名/电子邮箱',
        ];
    }
    public function rules(){
        return [
            ['loginname','required','message'=>'用户名或者邮箱不能为空','on'=>'login'],
            // ['username','required','message'=>'用户账号不能为空','on'=>['login','reg']],
            ['username','required','message'=>'用户账号不能为空','on'=>'reg'],
            ['userpass','required','message'=>'用户密码不能为空','on'=>['login','reg']],
            ['rememberMe','boolean','on'=>'login'],
            ['userpass','validatePass','on'=>'login'],
            ['useremail','required','message'=>'电子邮件不能为空','on'=>['reg','regbymail']],
            ['useremail','email','message'=>'电子邮箱格式不正确','on'=>['reg','regbymail']],
            ['useremail','unique','message'=>'电子邮箱已被注册','on'=>['reg','regbymail']],
            ['username','unique','message'=>'用户已被注册','on'=>'reg'],
            ['useremail','validateEmail','on'=>'seekpass'],
            ['repass','required','message'=>'确认密码不能为空','on'=>['reg']],
            ['repass','compare','compareAttribute'=>'userpass','message'=>'两次密码输入不一致','on'=>['reg']],
        ];
    }
    public function getProfile(){
        return $this->hasOne(Profile::className(),['userid'=>'userid']);
    }
/**
 * 验证密码
 */
    public function validatePass($attribute,$params){
        if(!$this->hasErrors())
        {
            $loginname = "username";
            if (preg_match('/@/', $this->loginname)) {
                $loginname = "useremail";
            }

            $data = self::find()->where($loginname.'=:user and userpass=:pass',[':user'=>$this->loginname,':pass'=>md5($this->userpass)])->one();

            if(is_null($data)){
                $this->addError('userpass','用户名或邮箱密码错误');
            }
        }
    }

    //验证邮箱
    public function validateEmail(){
        if(!$this->hasErrors()){
            $data=self::find()->where('username = :user and useremail = :email',[":user" => $this->username,":email" => $this->useremail])->one();
            if(is_null($data)){
                $this->addError("useremail","用户名或邮箱错误");
            }
        }
    }

    //登陆
    public function login($data){
       $this->scenario='login';
        if($this->load($data) && $this->validate()){
            $loginname = "username";
            if (preg_match('/@/', $this->loginname)) {
                $loginname = "useremail";
            }
            $userid=$this->find()->where($loginname.'=:user and userpass=:pass',[':user'=>$this->loginname,':pass'=>md5($this->userpass)])->one()->userid;
            $lifetime=$this->rememberMe?24*3600:0;
            $session = Yii::$app->session;
            session_set_cookie_params($lifetime);
            $session['user']=[
             'userid'=>$userid,
            'loginname' => $this->loginname,
            'isLogin' => 1,
            ];
            return (bool)$session['user']['isLogin'];
        }
        return false;
    }

    //发送邮箱
    public function seekPass($data){
        $this->scenario='seekpass';
        if($this->load($data) && $this->validate()){
            $time=time();
            $token=$this->createToken($data['Admin']['username'],$time);
            $mailer=Yii::$app->mailer->compose('seekpass',['username'=>$data['Admin']['username'],'time'=>$time,'token'=>$token]);
            $mailer->setFrom(Yii::$app->params['adminEmail']);
            $mailer->setTo($data['Admin']['useremail']);
            $mailer->setSubject("找回密码");
            if($mailer->send()){
                return true;
            }
        }
        return false;
    }

    //创建token
    public function createToken($username,$time){
        return md5(md5($username).base64_encode(Yii::$app->request->userIP).md5($time));
    }

    //改变密码
    public function changePass($data){
        $this->scenario='changepass';
        if($this->load($data) && $this->validate()){
            return (bool)$this->updateAll(['userpass'=>md5($this->userpass)],'username = :user',[':user'=>$this->username]);
        }
        return false;
    }

    //注册
    public function reg($data,$scenario='reg'){
        $this->scenario=$scenario;
        if($this->load($data) && $this->validate()){
            $this->createtime= time();
            $this->username=$data['User']['username'];
            $this->useremail=$data['User']['useremail'];
            $this->userpass = md5($data['User']['userpass']);
            if($this->save(false)){
                return true;
            }
            return false;
        }
        return false;
    }


    //邮箱注册
    public function regByMail($data,$scenario='regbymail'){
        $data['User']['username']='hrj_'.uniqid();
        $data['User']['userpass']=uniqid();
        $this->scenario=$scenario;
        if($this->load($data) && $this->validate()){
            $mailer=Yii::$app->mailer->compose('createuser',['username'=>$data['User']['username'],'userpass'=>$data['User']['userpass']]);
            $mailer->setFrom(Yii::$app->params['adminEmail']);
            $mailer->setTo($data['User']['useremail']);
            $mailer->setSubject("您成为了XXX会员！");
            if($mailer->send() && $this->reg($data,$scenario)){
                return true;
            }
        }
        return false;
    }
}
 ?>
